package com.itkaien.springzh.Mybatis;

import com.itkaien.springzh.Mybatis.mapper.UserMapper;
import com.itkaien.springzh.Mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.io.Reader;
import java.util.List;
//@SpringBootApplication
//@MapperScan("com.itkaien.springzh.Mybatis.mapper")
public class Mybatistest {
    public static void main(String[] args) {

        //1.读取配置文件
        String resource = "mybatis-config.xml";
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            //2.创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            //3.使用SqlSessionFactory创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //4.使用SqlSession执行数据库操作
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.findAll();
            users.forEach(System.out::println);
            //5.关闭SqlSession
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void TestDatasource(){

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        com.itkaien.springzh.Mybatis.UserService userService = context.getBean("userService",com.itkaien.springzh.Mybatis.UserService.class);
        userService.show();

    }
}
